<template>
  <div>
    <a-modal
      title="编辑幼儿信息"
      width="60%"
      :visible="visible"
      :confirmLoading="confirmLoading"
      @ok="handleSubmit"
      @cancel="handleCancel"
    >
      <a-spin :spinning="confirmLoading">
        <a-form :form="form">
          <a-form-item style="display: none;" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
            <a-input v-decorator="['id']" />
          </a-form-item>
          <a-row>
            <a-col :span="8">
              <a-form-item label="头像" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-upload
                  name="avatar"
                  list-type="picture-card"
                  class="avatar-uploader"
                  :show-upload-list="false"
                  :customRequest="customRequest"
                  :before-upload="beforeUpload"
                >
                  <img class="u-img" v-if="articleImage" :src="articleImage" alt="avatar" />
                  <div v-else>
                    <a-icon :type="uploadloading ? 'loading' : 'plus'" />
                    <div class="ant-upload-text">
                      上传图片
                    </div>
                  </div>
                </a-upload>
                <a-icon class="deleteimgicon" v-if="articleImage" @click="deleteImg" type="delete" />
                <span>（大小不要超过1M）</span>
                <!-- <CropUpload ref="cropUploadRef" :img-src="img" @successful="cropUploadSuccess" /> -->
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="8">
              <a-form-item label="幼儿姓名" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input
                  placeholder="请输入幼儿姓名"
                  v-decorator="['name', { rules: [{ required: true, message: '请输入幼儿姓名！' }] }]"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="学号" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
                <a-input
                  placeholder="请输入学号"
                  v-decorator="['studentNumber', { rules: [{ required: false, message: '请输入学号！' }] }]"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="班级" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
                <a-select
                  allowClear
                  placeholder="请选择班级！"
                  v-decorator="['classesId', { rules: [{ required: false, message: '请选择班级！' }] }]"
                >
                  <a-select-option v-for="item in classList" :key="item.id" :value="item.id">{{
                    item.name
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="8">
              <a-form-item label="出生日期" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
                <a-date-picker
                  class="fullwidth"
                  :format="dateFormat"
                  :valueFormat="dateFormat"
                  v-decorator="['birthday', { rules: [{ required: true, message: '请选择出生日期！' }] }]"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="性别" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
                <a-radio-group v-decorator="['gender', { rules: [{ required: true, message: '请选择幼儿性别' }] }]">
                  <a-radio :value="1">男</a-radio>
                  <a-radio :value="2">女</a-radio>
                  <a-radio :value="0">未知</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>

            <a-col :span="8">
              <a-form-item label="家庭住址" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
                <a-input
                  placeholder="请输入家庭住址"
                  type="textarea"
                  v-decorator="['homeAddress', { rules: [{ required: false, message: '请输入家庭住址！' }] }]"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
        <a-divider>家庭成员</a-divider>
        <s-table ref="familytable" :columns="columns" :data="loadfamilyData" :rowKey="record => record.id">
          <template slot="operator" v-if="hasPerm('children:add')">
            <a-button @click="$refs.addFamily.add(childId)" icon="plus" type="primary">添加家庭成员</a-button>
          </template>
          <span slot="action" slot-scope="text, record">
            <!-- <a v-if="hasPerm('children:edit')" @click="$refs.addFamily.edit(record)">编辑</a>
            <a-popconfirm
              v-if="hasPerm('children:leaveclass')"
              placement="topRight"
              title="关闭后，改成员不能使用微信端程序！"
              @confirm="() => shanchujiazhang(record)"
            >
              <a v-if="hasPerm('children:leaveclass')">关闭微信端</a>
            </a-popconfirm>
            <a-divider type="vertical" v-if="hasPerm('children:shifttransfers') & hasPerm('children:edit')" />
            <a-popconfirm
              v-if="hasPerm('children:leaveclass')"
              placement="topRight"
              title="重置后的密码为123456"
              @confirm="() => shanchujiazhang(record)"
            >
              <a v-if="hasPerm('children:leaveclass')">重置密码</a>
            </a-popconfirm>
            <a-divider type="vertical" v-if="hasPerm('children:shifttransfers') & hasPerm('children:deleterelation')" /> -->
            <a v-if="hasPerm('children:deleterelation')" @click="editParents(record)">编辑</a>
            <a-divider type="vertical" v-if="hasPerm('children:deleterelation')" />
            <a-popconfirm
              v-if="hasPerm('children:deleterelation')"
              placement="topRight"
              title="确定要删除吗？"
              @confirm="() => shanchujiazhang({ parentId: record.id, childId: childId })"
            >
              <a v-if="hasPerm('children:deleterelation')">删除</a>
            </a-popconfirm>
          </span>
        </s-table>
      </a-spin>
    </a-modal>
    <add-family ref="addFamily" @ok="handleOk" />
    <edit-family ref="editFamily" @ok="handleeditFamilyOk" />
  </div>
</template>

<script>
import { STable, XCard, XDown } from '@/components'
import { childrenEdit, childrenPage, childrenDeleteRelation } from '@/api/modular/children/childManage'
import { sysFileInfoUploadApp } from '@/api/modular/system/fileManage'
import { parentPage } from '@/api/modular/parent/parentManage'
import addFamily from './addFamily'
import editFamily from './editFamily'
import moment from 'moment'
export default {
  components: {
    XDown,
    XCard,
    STable,
    addFamily,
    editFamily
  },
  props: {
    classList: { type: Array }
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 }
      },

      // 表头
      columns: [
        {
          title: '家长姓名',
          dataIndex: 'name'
        },
        {
          title: '与幼儿关系',
          dataIndex: 'relationshipStr'
        },
        {
          title: '手机',
          dataIndex: 'phoneNumber'
        },
        {
          title: '工作单位',
          dataIndex: 'workplace'
        },
        {
          title: '学历',
          dataIndex: 'degreeStr'
        }
      ],
      childName: '',
      childId: '',
      loadfamilyData: parameter => {
        return parentPage(Object.assign(parameter, { Name: this.childName, ChildId: this.childId })).then(res => {
          return res.data
        })
      },
      visible: false,
      confirmLoading: false,
      form: this.$form.createForm(this),
      dateFormat: 'YYYY-MM-DD',
      uploadloading: false,
      articleImage: '',
      imgId: '',
      articleFile: null
    }
  },
  created() {
    this.columns.push({
      title: '操作',
      width: '100px',
      dataIndex: 'action',
      scopedSlots: { customRender: 'action' }
    })
  },
  methods: {
    // 初始化方法
    edit(record) {
      this.childName = record.name
      this.childId = record.id
      this.visible = true
      setTimeout(() => {
        this.form.setFieldsValue({
          id: record.id,
          name: record.name,
          studentNumber: record.studentNumber,
          gender: record.gender,
          homeAddress: record.homeAddress,
          classesId: record.classesId
        })
        this.articleImage = process.env.VUE_APP_API_BASE_URL + '/sysFileInfo/previewImg?id=' + record.imgId
        this.imgId = record.imgId
        this.form.getFieldDecorator('birthday', { initialValue: moment(record.birthday, 'YYYY-MM-DD') })
        this.$refs.familytable.refresh(true)
      }, 100)
    },
    async beforeUpload(file, fileList) {
      console.log(file)
      this.articleFile = file
      let src = await this.fileToBase64(file)
      console.log(src)
      this.articleImage = src
      // return false
    },
    customRequest(data) {
      console.log(this.form)
      const formData = new FormData()
      formData.append('file', data.file)
      sysFileInfoUploadApp(formData).then(res => {
        if (res.success) {
          this.$message.success('上传成功')
          this.articleImage = process.env.VUE_APP_API_BASE_URL + '/sysFileInfo/previewImg?id=' + res.data
          this.imgId = res.data
        } else {
          this.$message.error('上传失败：' + res.message)
        }
      })
    },
    fileToBase64(file) {
      return new Promise((resolve, reject) => {
        let reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = function(e) {
          resolve(e.target.result)
        }
      })
    },
    deleteImg() {
      this.articleImage = ''
      this.articleFile = null
      this.imgId = ''
    },
    classroomchange(val) {
      console.log(val)
      let _classroom = this.classroom1.find(item => {
        return item.id === val
      })
      this.classroomName = _classroom.cRoomName
    },
    editParents(item) {
      console.log(item)
      this.$refs.editFamily.edit(item, this.childId)
    },
    handleSubmit() {
      const {
        form: { validateFields }
      } = this
      this.confirmLoading = true
      validateFields((errors, values) => {
        if (!errors) {
          values['birthday'] = moment(values.birthday).format('YYYY-MM-DD')
          values['imgId'] = this.imgId
          childrenEdit(values)
            .then(res => {
              if (res.success) {
                this.$message.success('编辑成功')
                this.visible = false
                this.confirmLoading = false
                this.$emit('ok', values)
                this.form.resetFields()
              } else {
                this.$message.error('编辑失败：' + res.message)
              }
            })
            .finally(res => {
              this.confirmLoading = false
            })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.form.resetFields()
      this.visible = false
    },
    shanchujiazhang(param) {
      childrenDeleteRelation(param)
        .then(res => {
          if (res.success) {
            this.$message.success('删除成功')
            this.$refs.familytable.clearRefreshSelected()
          } else {
            this.$message.error('删除失败：' + res.message)
          }
        })
        .catch(err => {
          this.$message.error('删除错误：' + err.message)
        })
    },
    handleOk() {
      this.$refs.familytable.refresh(true)
    },
    handleeditFamilyOk() {
      this.$refs.familytable.refresh(true)
    }
  }
}
</script>
<style lang="less" scoped>
.u-img {
  display: inline-block;
  height: 100%;
  width: 100%;
}
</style>
